// main_process.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	const int MM_VIEW_SIZE = 100;
	// Before executing the line below, C:\ does not have
	// a file called "MMFTest.Dat"
	HANDLE hFile = CreateFile(TEXT("C:\\MMFTest.Dat"),
		GENERIC_READ | GENERIC_WRITE,
		FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS,
		FILE_ATTRIBUTE_NORMAL, NULL);

	// Before executing the line below, the MMFTest.Dat
	// file does exist but has a file size of 0 bytes.
	SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES)};
	sa.bInheritHandle = TRUE;
	HANDLE hFileMap = CreateFileMapping(hFile, &sa, PAGE_READWRITE,
		0, MM_VIEW_SIZE , NULL);

	// After executing the line above, the MMFTest.Dat
	// file has a size of 100 bytes.
	PVOID pvFile = MapViewOfFile(hFileMap, FILE_MAP_WRITE, 0, 0, MM_VIEW_SIZE);

	// Cleanup
	CloseHandle(hFile);


	// When the process terminates, MMFTest.Dat remains
	// on the disk with a size of 100 bytes.

	// create sub process
	char cmdline[MAX_PATH];
	sprintf(cmdline, "%d", hFileMap);

	STARTUPINFOA si={sizeof(si)};
	//GetStartupInfoA(&si);
	ZeroMemory(&si, sizeof(si));
	si.lpTitle = "sub_process";
	//si.dwFlags = STARTF_USESHOWWINDOW;

	PROCESS_INFORMATION pi;
	BOOL result = CreateProcessA("sub_process.exe", cmdline, NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &si,&pi);
	CloseHandle(pi.hProcess);
	CloseHandle(pi.hThread);

	do 
	{
		string cmd;
		cin >> cmd;
		strcpy((char*)pvFile, cmd.c_str());
		if (cmd == "q")
			break;
	} 
	while (true);

	UnmapViewOfFile(pvFile);
	CloseHandle(hFileMap);

	return 0;
}

